$(document).ready(function() {
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN'
    });
    
    // 初始化数据表格
    var transactionTable = $('#transactionTable').DataTable({
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        ajax: {
            url: '/api/transaction/list',
            dataSrc: function(res) {
                if (res.code === 200) {
                    return res.data || [];
                } else {
                    toastr.error('获取交易记录失败：' + res.message);
                    return [];
                }
            }
        },
        columns: [
            { data: 'transactionCode' },
            { 
                data: 'transactionType',
                render: function(data) {
                    var types = {
                        'IN': '采购入库',
                        'OUT': '销售出库',
                        'TRANSFER': '库存调拨',
                        'CHECK': '库存盘点'
                    };
                    return types[data] || data;
                }
            },
            { data: 'productName' },
            { data: 'quantity' },
            { data: 'unit' },
            { 
                data: 'amount',
                render: function(data) {
                    return '¥' + parseFloat(data).toFixed(2);
                }
            },
            { 
                data: 'warehouseName',
                render: function(data, type, row) {
                    if (row.transactionType === 'TRANSFER' && row.targetWarehouseName) {
                        return data + ' → ' + row.targetWarehouseName;
                    }
                    return data;
                }
            },
            { 
                data: 'status',
                render: function(data) {
                    var statusClasses = {
                        'PENDING': 'status-pending',
                        'PROCESSING': 'status-pending',
                        'COMPLETED': 'status-completed',
                        'CANCELLED': 'status-cancelled'
                    };
                    var statusNames = {
                        'PENDING': '待处理',
                        'PROCESSING': '处理中',
                        'COMPLETED': '已完成',
                        'CANCELLED': '已取消'
                    };
                    return '<span class="' + (statusClasses[data] || '') + '">' + 
                           (statusNames[data] || data) + '</span>';
                }
            },
            { 
                data: 'createTime',
                render: function(data) {
                    return new Date(data).toLocaleString();
                }
            },
            {
                data: null,
                render: function(data, type, row) {
                    var btns = '<button class="btn btn-sm btn-info view-btn mr-1" data-id="' + row.transactionId + '">查看</button>';
                    
                    if (row.status !== 'COMPLETED' && row.status !== 'CANCELLED') {
                        btns += '<button class="btn btn-sm btn-primary edit-btn mr-1" data-id="' + row.transactionId + '">编辑</button>';
                        btns += '<button class="btn btn-sm btn-success complete-btn mr-1" data-id="' + row.transactionId + '">完成</button>';
                        btns += '<button class="btn btn-sm btn-danger delete-btn" data-id="' + row.transactionId + '">删除</button>';
                    }
                    
                    return btns;
                }
            }
        ]
    });
    
    // 查询按钮点击事件
    $('#searchBtn').click(function() {
        var params = {
            transactionType: $('#transactionType').val(),
            productName: $('#productName').val(),
            warehouseId: $('#warehouseSelect').val(),
            status: $('#transactionStatus').val(),
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val()
        };
        
        transactionTable.ajax.url('/api/transaction/list?' + $.param(params)).load();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').click(function() {
        $('#transactionType').val('');
        $('#productName').val('');
        $('#warehouseSelect').val('');
        $('#transactionStatus').val('');
        $('#startDate').val('');
        $('#endDate').val('');
        
        transactionTable.ajax.url('/api/transaction/list').load();
    });
    
    // 查看按钮点击事件
    $('#transactionTable').on('click', '.view-btn', function() {
        var id = $(this).data('id');
        
        $.ajax({
            url: '/api/transaction/' + id,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    
                    // 构建交易详情HTML
                    var detailsHtml = `
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>交易编号：</strong> ${data.transactionCode}
                            </div>
                            <div class="col-md-6">
                                <strong>交易类型：</strong> ${data.transactionTypeName}
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>产品名称：</strong> ${data.productName}
                            </div>
                            <div class="col-md-6">
                                <strong>数量：</strong> ${data.quantity} ${data.unit}
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>金额：</strong> ¥${parseFloat(data.amount).toFixed(2)}
                            </div>
                            <div class="col-md-6">
                                <strong>仓库：</strong> ${data.warehouseName}
                            </div>
                        </div>`;
                        
                    if (data.transactionType === 'TRANSFER' && data.targetWarehouseName) {
                        detailsHtml += `
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>目标仓库：</strong> ${data.targetWarehouseName}
                            </div>
                            <div class="col-md-6"></div>
                        </div>`;
                    }
                    
                    detailsHtml += `
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong>交易状态：</strong> ${data.statusName}
                            </div>
                            <div class="col-md-6">
                                <strong>创建时间：</strong> ${new Date(data.createTime).toLocaleString()}
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <strong>交易备注：</strong>
                                <p>${data.remark || '无'}</p>
                            </div>
                        </div>`;
                    
                    if (data.logs && data.logs.length > 0) {
                        detailsHtml += `
                        <div class="row">
                            <div class="col-md-12">
                                <strong>交易流程：</strong>
                                <ul class="list-group">`;
                        
                        data.logs.forEach(function(log) {
                            detailsHtml += `<li class="list-group-item">${new Date(log.createTime).toLocaleString()} - ${log.content}</li>`;
                        });
                        
                        detailsHtml += `
                                </ul>
                            </div>
                        </div>`;
                    }
                    
                    $('#transactionDetails').html(detailsHtml);
                    $('#transactionModal').modal('show');
                } else {
                    toastr.error('加载交易详情失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('加载交易详情失败：' + xhr.statusText);
            }
        });
    });
    
    // 删除按钮点击事件
    $('#transactionTable').on('click', '.delete-btn', function() {
        var id = $(this).data('id');
        
        if (confirm('确定要删除此交易记录吗？')) {
            $.ajax({
                url: '/api/transaction/' + id,
                type: 'DELETE',
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success('删除成功');
                        transactionTable.ajax.reload();
                    } else {
                        toastr.error('删除失败：' + res.message);
                    }
                },
                error: function(xhr) {
                    toastr.error('删除失败：' + xhr.statusText);
                }
            });
        }
    });
    
    // 完成按钮点击事件
    $('#transactionTable').on('click', '.complete-btn', function() {
        var id = $(this).data('id');
        
        if (confirm('确定要将此交易标记为已完成吗？')) {
            $.ajax({
                url: '/api/transaction/' + id + '/complete',
                type: 'PUT',
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success('操作成功');
                        transactionTable.ajax.reload();
                    } else {
                        toastr.error('操作失败：' + res.message);
                    }
                },
                error: function(xhr) {
                    toastr.error('操作失败：' + xhr.statusText);
                }
            });
        }
    });
    
    // 编辑按钮点击事件
    $('#transactionTable').on('click', '.edit-btn', function() {
        var id = $(this).data('id');
        
        $.ajax({
            url: '/api/transaction/' + id,
            type: 'GET',
            success: function(res) {
                if (res.code === 200) {
                    var data = res.data;
                    
                    // 填充表单
                    $('#transactionId').val(data.transactionId);
                    $('#modalTransactionType').val(data.transactionType);
                    $('#modalProductId').val(data.productId);
                    $('#modalQuantity').val(data.quantity);
                    $('#modalUnit').val(data.unit);
                    $('#modalAmount').val(data.amount);
                    $('#modalWarehouseId').val(data.warehouseId);
                    
                    if (data.transactionType === 'TRANSFER' && data.targetWarehouseId) {
                        $('#modalTargetWarehouseId').val(data.targetWarehouseId);
                        $('#modalTargetWarehouseId').closest('.col-md-6').show();
                    } else {
                        $('#modalTargetWarehouseId').val('');
                        $('#modalTargetWarehouseId').closest('.col-md-6').hide();
                    }
                    
                    $('#modalStatus').val(data.status);
                    $('#modalTransactionDate').datepicker('setDate', new Date(data.transactionDate || data.createTime));
                    $('#modalRemark').val(data.remark);
                    
                    // 显示模态框
                    $('#addEditTransactionModalLabel').text('编辑交易');
                    $('#addEditTransactionModal').modal('show');
                } else {
                    toastr.error('加载交易详情失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error('加载交易详情失败：' + xhr.statusText);
            }
        });
    });
    
    // 新增交易按钮点击事件
    $('#addBtn').click(function() {
        // 重置表单
        $('#transactionForm')[0].reset();
        $('#transactionId').val('');
        
        // 初始化日期为今天
        $('#modalTransactionDate').datepicker('setDate', new Date());
        
        // 隐藏目标仓库
        $('#modalTargetWarehouseId').closest('.col-md-6').hide();
        
        // 显示模态框
        $('#addEditTransactionModalLabel').text('新增交易');
        $('#addEditTransactionModal').modal('show');
    });
    
    // 交易类型变化时显示/隐藏目标仓库
    $('#modalTransactionType').change(function() {
        if ($(this).val() === 'TRANSFER') {
            $('#modalTargetWarehouseId').closest('.col-md-6').show();
        } else {
            $('#modalTargetWarehouseId').closest('.col-md-6').hide();
        }
    });
    
    // 保存交易按钮点击事件
    $('#saveTransactionBtn').click(function() {
        // 表单验证
        if (!$('#transactionForm')[0].checkValidity()) {
            $('#transactionForm')[0].reportValidity();
            return;
        }
        
        // 收集表单数据
        var formData = {
            transactionType: $('#modalTransactionType').val(),
            productId: parseInt($('#modalProductId').val(), 10),
            quantity: parseFloat($('#modalQuantity').val()),
            unit: $('#modalUnit').val(),
            amount: parseFloat($('#modalAmount').val()),
            warehouseId: parseInt($('#modalWarehouseId').val(), 10),
            status: $('#modalStatus').val(),
            transactionDate: $('#modalTransactionDate').val(),
            remark: $('#modalRemark').val()
        };
        
        // 如果是调拨交易，添加目标仓库
        if (formData.transactionType === 'TRANSFER') {
            formData.targetWarehouseId = parseInt($('#modalTargetWarehouseId').val(), 10);
        }
        
        // 如果是编辑，添加ID
        var transactionId = $('#transactionId').val();
        if (transactionId) {
            formData.transactionId = parseInt(transactionId, 10);
        }
        
        // 获取CSRF令牌
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        
        // 发送请求保存交易
        $.ajax({
            url: '/api/transaction/save',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            beforeSend: function(xhr) {
                // 添加CSRF令牌到请求头
                if (token && header) {
                    xhr.setRequestHeader(header, token);
                }
            },
            success: function(res) {
                if (res.code === 200) {
                    toastr.success(transactionId ? '更新成功' : '添加成功');
                    $('#addEditTransactionModal').modal('hide');
                    transactionTable.ajax.reload();
                } else {
                    toastr.error((transactionId ? '更新' : '添加') + '失败：' + res.message);
                }
            },
            error: function(xhr) {
                toastr.error((transactionId ? '更新' : '添加') + '失败：' + xhr.responseText);
            }
        });
    });
    
    // 导出按钮点击事件
    $('#exportBtn').click(function() {
        var params = {
            transactionType: $('#transactionType').val(),
            productName: $('#productName').val(),
            warehouseId: $('#warehouseSelect').val(),
            status: $('#transactionStatus').val(),
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val()
        };
        
        window.location.href = '/api/transaction/export?' + $.param(params);
    });
    
    // 加载仓库下拉框选项
    $.ajax({
        url: '/api/warehouse/list',
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                var options = '';
                res.data.forEach(function(warehouse) {
                    options += '<option value="' + warehouse.warehouseId + '">' + warehouse.warehouseName + '</option>';
                });
                $('#warehouseSelect').append(options);
                $('#modalWarehouseId').append(options);
                $('#modalTargetWarehouseId').append(options);
            }
        }
    });
    
    // 加载产品下拉框选项
    $.ajax({
        url: '/api/product/list',
        type: 'GET',
        success: function(res) {
            if (res.code === 200 && res.data) {
                var options = '';
                res.data.forEach(function(product) {
                    options += '<option value="' + product.productId + '">' + product.productName + '</option>';
                });
                $('#modalProductId').append(options);
            }
        }
    });
    
    // 产品选择变更时自动填充单位
    $('#modalProductId').change(function() {
        var productId = $(this).val();
        if (!productId) {
            $('#modalUnit').val('');
            return;
        }
        
        $.ajax({
            url: '/api/product/' + productId,
            type: 'GET',
            success: function(res) {
                if (res.code === 200 && res.data) {
                    $('#modalUnit').val(res.data.unit);
                }
            }
        });
    });
}); 